<template>
	<div>
		<div class="container">
			<div class="handle-box">
				<!-- <el-select v-model="data.now_name" placeholder="地址" class="handle-select mr10"  @change="systemFlagChange">
					<el-option v-for="item in data.systemFlags" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
				</el-select> -->
				<el-input v-model="data.name" placeholder="用户名" class="handle-input mr10"></el-input>
				<el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
				<el-button type="primary" :icon="Plus" @click="addRole">新增</el-button>
			</div>
			<el-table :data="data.historyData" border class="table" ref="multipleTable" header-cell-class-name="table-header">
				<el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
				<el-table-column prop="username" label="用户名"></el-table-column>
				<!-- <el-table-column prop="user_id" label="用户名" v-if="false"></el-table-column> -->
				<el-table-column prop="order_sn" label="订单编号"></el-table-column>
				<!-- <el-table-column prop="goods_id" label="商品名称" v-if="false"></el-table-column> -->
				<el-table-column prop="goodsname" label="商品名称"></el-table-column>
				<el-table-column prop="expire_at" label="过期时间"></el-table-column>
				<!-- <el-table-column prop="coupon_id" label="优惠券"></el-table-column> -->
				<!-- <el-table-column prop="origin_amount" label="原价"></el-table-column> -->
				<el-table-column prop="amount" label="实价"></el-table-column>
				<el-table-column label="支付方式" align="center">
					<template #default="scope">
						<el-tag
							:type="scope.row.status == '1' ? 'warning' : scope.row.status == '2' ?'success': ''"
						>
							{{ scope.row.status=='1'? '余额支付':scope.row.status=='2'? '第三方支付':'未支付'}}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="订单状态" align="center">
					<template #default="scope">
						<el-tag
							:type="scope.row.status == '2' ? 'success' : scope.row.status == '-1' ?'info' : scope.row.status == '0' ?'danger' : scope.row.status == '1' ? 'warning' : ''"
						>
							{{ scope.row.status=='-1'? '已关闭':scope.row.status=='0'? '待支付':scope.row.status=='1'? '已支付待确认':scope.row.status=='2'? '已完成':'失效'}}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="created_at" label="创建时间"></el-table-column>
			
				
			<el-table-column label="操作" width="220" align="center">
					<template #default="scope">
						<el-button text :icon="Edit" @click="handleClick(scope.$index, scope.row)" v-permiss="15">
							编辑
						</el-button>
						<el-button text :icon="Delete" class="red" @click="deleteCommon(scope.$index, scope.row)" v-permiss="16">
							删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div class="pagination">
				<el-pagination
     				 @size-change="handleSizeChange"
    				  @current-change="handleCurrentChange"
	  				:current-page="data.curPage"
					:page-sizes="[10, 20, 30, 40]"
					:page-size="data.pageSize"
					:total="data.dataCount"
      layout="total, sizes, prev, pager, next, jumper"
     >
    </el-pagination>
			</div>
		</div>

		<addMenuPage v-on:onItemChange="getAllDatas" ref="addMenu"></addMenuPage>
	</div>
</template>

<script setup lang="ts" name="basetable">

import addMenuPage from "./children/order/addtable.vue";
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { Delete, Edit, Search, Plus } from '@element-plus/icons-vue';
import { BASE_API ,orderData} from '../api/index';
// 引入day.js
import dayjs from 'dayjs'

// 方法中-时间戳转时间
const formatTime = (rowtime: any,column: any) => {
  var date = rowtime[column.property];
//   console.log(column.property)
  if (date == undefined) {
    return '';
  }
  date = Number(date+'000');
//   console.log(typeof date)
  return dayjs(date).format('YYYY-MM-DD')
}

const addMenu = ref(); //ref方法是让我们的简单类型数据变成响应式数据；在方法里改变时需要.value来获取
interface User {
		id: number;
		user_id: string;
        username: string;
		order_sn: string;
		goods_id: string;
        goodsname: string;
		expire_at: string;
		coupon_id:string;
		origin_amount:string;
		amount:string;
		pay_way:string;
		status:string;
		created_at:string;
    }
    // reactive 数据双向绑定；让我们的复杂类型数据变成响应式数据；不需要.value来获取
    const data = reactive({
        dataText: "", //表格开始置空
        dataCount: 0, //共几条
        pageSize: 10, // 每页显示多少条
        curPage: 1, //第几页
        now_name: "",
		name: "",
        systemFlags: [{
            name: '集约式直饮水智能售水系统',
            id: 'water'
        }, {
            name: '污染源在线监测平台',
            id: 'pollution'
        }],
        historyData: [], //回显到表格的数据
        small: false,
    });
    //获取初始数据
    onMounted(() => {
        if (localStorage.getItem("systemFlag") == undefined) {
            data.now_name = data.systemFlags[0].id;
        } else {
            data.now_name = localStorage.getItem("systemFlag") || '';
        };
        getAllDatas()
    });
    const systemFlagChange = (val: string) => {
        localStorage.setItem("systemFlag", val)
        getAllDatas();
    };
    //表格初始查询
    const getAllDatas = () => {
        data.dataText = "";
        data.historyData = [];
        data.curPage = 1;
        getAllListLink();
    };
	   const getguiling = () => {
		localStorage.setItem("systemFlag", '')
		let data ={
			now_name: "",//搜索框运行完归零。清空
		}
		let params = {
            systemFlag: '',//搜索框清空
        }
	   }
    //获取表格列表数据
    const getAllListLink = () => {
        let params = {
			action:'apiindex',
			sort:'id',
			order:'desc',
			name:data.name,//搜索框
            systemFlag: data.now_name,//搜索框
            pageNum: data.curPage, //第几页
            pageSize: data.pageSize,// 每页显示多少条
        }
			
		orderData(params).then(res => {
			console.log(res);
			getguiling();
            if (res.status == 200) {
                data.dataCount = res.data.total
                if (res.data.total != 0) {
                    data.historyData = res.data.rows;
					console.log(data.historyData)
					// BASE_API
                } else {
                    data.dataText = "暂无数据";
                }
            } else if (res.status !== 200) {
                data.dataText = "暂无数据";
                ElMessage({
                    showClose: true,
                    message: res.statusText,
                    type: 'error',
                })
            }
        })
    };
    //分页改变
    const changepage = (index: number) => {
        data.curPage = index;
        getAllListLink();
    };
    //每页条数切换
    const handleSizeChange = (val: number) => {
        // data.curPage = 1;
        data.pageSize = val;
        getAllListLink();
    };
	    //当前页数切换
	    const handleCurrentChange = (val: number) => {
        data.curPage = val;
        // data.pageSize = 10;
        getAllListLink();
    };

    //删除-接口
    const deleteCommon = (idnex: number,row: User) => {
        let params = {
			action:'apidel',
            id: row.id
        }

        orderData(params).then(res => {
			console.log(res)
			    if (res.status == 200) {
                    ElMessage({
                        showClose: true,
                        message: '操作成功',
                        type: 'success',
                    })
                    getAllDatas();
                } else if (res.status !== 200) {
                    ElMessage({
                        showClose: true,
                        message: res.data.msg,
                        type: 'error',
                    })
                }
            })
    };
    //添加
    const addRole = () => {
        addMenu.value.addItemShow(data.now_name)
    };
    //编辑
    const handleClick = (index: number, row: any) => {
        addMenu.value.addItemShow2(row, index)
    };

//参考 https://blog.csdn.net/Hei_lovely_cat/article/details/126105403

// const tableData = ref<TableItem[]>([]);
// const pageTotal = ref(0);
// 获取表格数据
// 查询操作
const handleSearch = () => {
	console.log(data.name)
localStorage.setItem("systemFlag", data.name)
        getAllDatas();
};


let datas = {
	action:'apiindex',
    pageIndex: 1,//当前页数，支持 .sync 修饰符	 number
	pageSize: 10//每页显示条目个数，支持 .sync 修饰符 number
};

// 获取表格数据
// const getData= () => {
// 	adminbData(datas).then((res) => {
// 		pageTotal.value = res.data.total || 50;
// 		console.log(res.data)
//             });
	
// };
// getData();

// 删除操作
// const handleDelete = (index: number) => {
// 	// 二次确认删除
// 	ElMessageBox.confirm('确定要删除吗？', '提示', {
// 		type: 'warning'
// 	})
// 		.then(() => {
// 			ElMessage.success('删除成功');
// 			// data.historyData.value.splice(index, 1);
// 		})
// 		.catch(() => {});
// };

// 表格编辑时弹窗和保存
const editVisible = ref(false);
let form = reactive({
	name: '',
	address: ''
});
let idx: number = -1;
const handleEdit = (index: number, row: any) => {
	idx = index;
	form.name = row.name;
	form.address = row.address;
	editVisible.value = true;
};
const saveEdit = () => {
	editVisible.value = false;
	ElMessage.success(`修改第 ${idx + 1} 行成功`);
	// data.historyData.value[idx].name = form.name;
	// data.historyData.value[idx].address = form.address;
};

</script>

<style scoped>
.handle-box {
	margin-bottom: 20px;
}

.handle-select {
	width: 120px;
}

.handle-input {
	width: 300px;
}
.table {
	width: 100%;
	font-size: 14px;
}
.red {
	color: #F56C6C;
}
.mr10 {
	margin-right: 10px;
}
.table-td-thumb {
	display: block;
	margin: auto;
	width: 40px;
	height: 40px;
}
</style>
